package com.sxt.service.impl;


import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Service;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.sxt.model.SmsMessage;
import com.sxt.service.SmsService;

import cn.hutool.json.JSONUtil;

@Service
public class SmsServiceImpl implements SmsService ,MessageListener{

	private static final Logger log = LoggerFactory.getLogger(SmsServiceImpl.class) ;
	@Autowired
	private IAcsClient  client ;
	
	@JmsListener(destination = "sms.msg.queue") // body bady
	public void onMessage(Message message) {
		ObjectMessage objMsg = (ObjectMessage) message ;
		SmsMessage smsMessage;
		try {
			smsMessage = (SmsMessage)objMsg.getObject();
			 sendSms(smsMessage);
		} catch (JMSException e) {
			log.error("短信发送失败，本地短信为{}",JSONUtil.toJsonPrettyStr(objMsg));
			e.printStackTrace();
		}
	}
	
	@Override
	public void sendSms(SmsMessage message) {
		CommonRequest request = new CommonRequest();
		request.setSysMethod(MethodType.POST);
		request.setSysDomain("dysmsapi.aliyuncs.com");
		request.setSysVersion("2017-05-25");
		request.setSysAction("SendSms");
		request.putQueryParameter("RegionId", "cn-hangzhou");
		request.putQueryParameter("PhoneNumbers", message.getPhoneNumbers());
		request.putQueryParameter("SignName", message.getSignName());
		request.putQueryParameter("TemplateCode", message.getTemplateCode());
		request.putQueryParameter("TemplateParam",JSONUtil.toJsonStr(message.getTemplateParam()));
		try {
			CommonResponse response = client.getCommonResponse(request);
			System.out.println(response.getData());
		} catch (ServerException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		}		
	}


}
